//
//  CZOAuthView.swift
//  weibo27
//
//  Created by mac on 16/4/17.
//  Copyright © 2016年 it.cast. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZOAuthView: UIViewController {
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        //替换根视图
        view = webView
        
        //设置代理
        
        webView.delegate = self
        //不设置背景颜色，可能会有卡顿的现象。
        view.backgroundColor = UIColor.whiteColor()
        
        self.title = "登录授权页"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closeOAuthView")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoLogin")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //加载授权页   在这里显示是授权页
        self.webView.loadRequest(NSURLRequest(URL: NetTools.shareTools.OAthth))
    }
    
    // MARK: 关闭授权页面
    @objc private func closeOAuthView(){
        
        navigationController?.dismissViewControllerAnimated(true, completion: nil)

        //关闭
        SVProgressHUD.dismiss()
    }
    
    // MARK: 自动填充登录
    @objc private func autoLogin(){
        
        let js = "document.getElementById('userId').value = '18612369294';" + "document.getElementById('passwd').value = '425830lzl';"
        //让webview自动加载
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
}

// MARK - UIWebViewDelegate
extension CZOAuthView:UIWebViewDelegate{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //主机不是www.baidu.com就继续加载页面，如果不是www.baidu.com就返回false，不加载
        guard let url = request.URL where url.host == "www.baidu.com" else{
            
            return true
        }
        
        guard let query = url.query where query.hasPrefix("code=") else{
            print("取消授权")
            
            SVProgressHUD.dismiss()
            
            closeOAuthView()
            
            return false
        }
        
        //获取code
        let code = query.substringFromIndex("code=".endIndex)
        
        //获取accessToken
        CZUserAccountViewModel.shareModel.loadUserInfo(code) { (isSuccess) -> () in
            if !isSuccess {
            
                SVProgressHUD.showInfoWithStatus("你的网络比给力")
                
                //调用延迟函数 闭包的使用
                delay(1.0) { self.closeOAuthView() }
                
                
                return
            }
            // 让控制器消失  通知中心是同步的先执行方法，在执行后续的代码
            self.dismissViewControllerAnimated(false){
                
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "welcome")
            }
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}

































